// AppIndexer: Build in-memory index of installed apps (Windows-first)
const fs = require('fs')
const path = require('path')
const os = require('os')

function walk(dir, predicate) {
  const results = []
  try {
    const entries = fs.readdirSync(dir, { withFileTypes: true })
    for (const entry of entries) {
      const full = path.join(dir, entry.name)
      if (entry.isDirectory()) {
        results.push(...walk(full, predicate))
      } else if (predicate(full)) {
        results.push(full)
      }
    }
  } catch (_) {}
  return results
}

function resolveStartMenuDirs() {
  const dirs = []
  // System-wide start menu
  dirs.push('C:/ProgramData/Microsoft/Windows/Start Menu/Programs')
  // User-specific start menu
  const home = os.homedir()
  dirs.push(path.join(home, 'AppData/Roaming/Microsoft/Windows/Start Menu/Programs'))
  return dirs
}

class AppIndexer {
  constructor() {
    this.items = [] // { id,name,path,type:'app', lastUpdated }
  }

  buildIndex() {
    const now = Date.now()
    const dirs = resolveStartMenuDirs()
    const exts = ['.lnk', '.url']
    const isTarget = (p) => exts.includes(path.extname(p).toLowerCase())

    const indexed = []
    for (const d of dirs) {
      const files = walk(d, isTarget)
      for (const file of files) {
        const name = path.basename(file, path.extname(file))
        indexed.push({ id: file, name, path: file, type: 'app', lastUpdated: now })
      }
    }

    // Deduplicate by name+path
    const uniq = new Map()
    for (const it of indexed) {
      const key = `${it.name}|${it.path}`
      if (!uniq.has(key)) uniq.set(key, it)
    }
    this.items = Array.from(uniq.values())
    return this.items
  }

  getAll() { return this.items }
}

module.exports = { AppIndexer }
